package com.dinghui.mybatis.interceptor;


import com.dinghui.mybatis.annotation.Login;
import com.dinghui.mybatis.config.ResultCode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一些页面需要做登录检查
 *
 * @author zifangsky
 * @date 2018/7/26
 * @since 1.0.0
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 检查是否已经登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isLogin = false;
//        System.out.println("进入LoginInterceptor");
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Login login = method.getMethod().getDeclaredAnnotation(Login.class);

            //需要登录
            if (login != null) {
                isLogin = true;
            } else {
                login = method.getBeanType().getDeclaredAnnotation(Login.class);
                isLogin = login != null;
            }
            if (isLogin){
                String token = null;
                token = request.getHeader("ACCESSTOKEN");
                ValueOperations<String, Object> valueOperation = redisTemplate.opsForValue();
                Object object2 = valueOperation.get(token + ":user");
                if (object2 == null) {
                    ResultCode.TOKEN_STALE.throwBizException();
                }
            }
        }
        return true;
    }

}
